package com.gexin.service.memberAcitivty;

import com.alibaba.fastjson.JSONObject;
import com.gexin.common.model.ApiResponse;
import com.gexin.common.utils.ArithUtil;
import com.gexin.common.utils.BigDecimalUtils;
import com.gexin.common.utils.BigDecimalUtilsIfNull;
import com.gexin.model.activity.*;
import com.gexin.model.enums.MemberInfoEnum;
import com.gexin.model.enums.MemberOrderItergralStatusEnum;
import com.gexin.model.order.Order;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.alipay.util.RandomUtils.randomDouble;

@Slf4j
public class MemberActivityService {


    /**
     * 个人积分信息
     *
     * @param authUser
     * @return
     */
    public ApiResponse getBillOfShop(String authUser) {
        MemberBillSpeedIntegral memberBillSpeedIntegral = MemberBillSpeedIntegral.dao.getMemberBillSpeedIntegralByUserId(authUser);
        if (memberBillSpeedIntegral == null) {
            memberBillSpeedIntegral = new MemberBillSpeedIntegral();
            memberBillSpeedIntegral.setUserIdAndSpeedIntegralAndCoinAndBillCouponAndForecastAndRemainAndReverseAndDailyIncrement(
                    authUser, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
                    BigDecimal.ZERO, BigDecimal.ZERO);
            memberBillSpeedIntegral.save();
        }
        return new ApiResponse(true, "返回成功", memberBillSpeedIntegral);
    }

    /**
     * 簽到釋放倍數
     *
     * @param reverse
     * @return
     */
    public static BigDecimal getRandomRule(ReverseMultipleRule reverse) {
        double min = 0;
        double max = 0;
        if (reverse != null) {
            min = reverse.getReverseMultipleMin().doubleValue();
            max = reverse.getReverseMultipleMax().doubleValue();
        }
        BigDecimal bigDecimal = randomDouble(min, max).setScale(3, RoundingMode.HALF_UP);
        return bigDecimal;
    }

    /**
     * 判断当前已获得的积分是否大于0并且已获得积分小于本单的总积分(兑货券和倍数的积,1.5,3倍封顶)
     *
     * @param memberOrderList 会员积分订单列表
     * @return topOff 封顶倍数
     */
    public List<MemberOrder> nextLink(List<MemberOrder> memberOrderList, BigDecimal topOff) {
        if (CollectionUtils.isEmpty(memberOrderList)) {
            return memberOrderList;
        }
        List<MemberOrder> collect = memberOrderList.stream().filter(memberOrder -> {
            BigDecimal initAcquireIntegral = BigDecimal.ZERO;
            BigDecimal integral = memberOrder.getBillIntegral() == null ? BigDecimal.ZERO : memberOrder.getBillIntegral();
            BigDecimal billIntegralAndmultiReserveMultiply = integral.multiply(topOff);
            BigDecimal acquiredIntegral = memberOrder.getAcquiredIntegral() == null ? BigDecimal.ZERO : memberOrder.getAcquiredIntegral();
            if (BigDecimalUtils.greaterEqual(acquiredIntegral, initAcquireIntegral) && BigDecimalUtils.lessThan(acquiredIntegral, billIntegralAndmultiReserveMultiply)) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 封顶倍数
     *
     * @param auth
     * @return
     */
    public BigDecimal getGarde(String auth) {
        ReverseMultipleRule reverseMultipleRule = ReverseMultipleRule.dao.getReverse();
        InviteeRelative inviteeRelativeAdmin = InviteeRelative.dao.getInviteeRelative(auth);
        BigDecimal reverseMultipleCount = new BigDecimal("0");
        if (inviteeRelativeAdmin != null) {
            String inviterId = inviteeRelativeAdmin.getId();
            List<InviteeRelative> inviteeRelativeLeafList = inviteeRelativeAdmin.findByInviterId(inviterId);

            List<MemberInfo> fansMemberInfoList = MemberInfo.dao.memberFankeInfoList(MemberInfoEnum.SECOND_LEVEL.getCode(),
                    MemberInfoEnum.THIRD_LEVEL.getCode());
            Map<String, MemberInfo> fansMemberInfoMap = fansMemberInfoList.stream().filter(memberInfo -> memberInfo.getUserId() != null)
                    .collect(Collectors.toMap(MemberInfo::getUserId, Function.identity(), (key1, key2) -> key2));

            List<InviteeRelative> collect = inviteeRelativeLeafList.stream().filter(inviteeChildrenRelative -> inviteeChildrenRelative.
                    getUserId() != null && fansMemberInfoMap.containsKey(inviteeChildrenRelative.getUserId())).collect(Collectors.toList());
            if (collect.size() >= 2) {
                reverseMultipleCount = reverseMultipleRule.getReverseMultipleCountMax();
            } else {
                reverseMultipleCount = reverseMultipleRule.getReverseMultipleCountMin();
            }
        } else {
            reverseMultipleCount = reverseMultipleRule.getReverseMultipleCountMin();
        }
        return reverseMultipleCount;
    }


    /**
     * 递归从最小开始
     * 不需要判断是不是补单的第一单,因为就是剩下的值,需要计算暂存剩下了多少
     *
     * @param topOff
     * @param
     */
    public BigDecimal recurrentTask(BigDecimal topOff, MemberOrder memberOrder,
                                    BigDecimal currentGeneratedIntegral, List<MemberOrder> memberOrderList) {

        if (BigDecimalUtils.lessEqual(currentGeneratedIntegral, BigDecimal.ZERO)) {
            return BigDecimal.ZERO;
        }
        BigDecimal acquiredIntegral = memberOrder.getAcquiredIntegral();
        BigDecimal dailyIncrement = memberOrder.getDailyIncrement() == null ? BigDecimal.ZERO : memberOrder.getDailyIncrement();
        BigDecimal remainIntegral = memberOrder.getRemainIntegral() == null ? BigDecimal.ZERO : memberOrder.getRemainIntegral();
        BigDecimal billIntegral = memberOrder.getBillIntegral() == null ? BigDecimal.ZERO : memberOrder.getBillIntegral();
//        BigDecimal forcastIntegral = billIntegral.multiply(topOff);
        BigDecimal currentRemainIntegral = BigDecimal.ZERO;
//        if (BigDecimalUtils.lessThan(remainIntegral, BigDecimal.ZERO)) {
//            return BigDecimal.ZERO;
//        }
//      今天增加的积分还有多少没有加到订单里边(多出来那一部分)
        if (BigDecimalUtils.lessThan(remainIntegral.subtract(currentGeneratedIntegral), BigDecimal.ZERO)) {
            currentRemainIntegral = currentGeneratedIntegral.subtract(remainIntegral);
            acquiredIntegral = acquiredIntegral.add(remainIntegral);
            dailyIncrement = remainIntegral;
            remainIntegral = BigDecimal.ZERO;
            memberOrder.setStatus(MemberOrderItergralStatusEnum.DESTORY.getCode());
        } else {
            int status = memberOrder.getStatus() == null ? 0 : memberOrder.getStatus();
            if (MemberOrderItergralStatusEnum.CONFIRM_THE_RECEIVE.getCode() == status) {
                memberOrder.setStatus(MemberOrderItergralStatusEnum.GET_INTEGRAL.getCode());
            }
            currentRemainIntegral = BigDecimal.ZERO;
            remainIntegral = remainIntegral.subtract(currentGeneratedIntegral);
            acquiredIntegral = acquiredIntegral.add(currentGeneratedIntegral);
            dailyIncrement = currentGeneratedIntegral;
        }
        memberOrder.setAcquiredIntegral(acquiredIntegral);
        memberOrder.setDailyIncrement(dailyIncrement);
        memberOrder.setRemainIntegral(remainIntegral);
        memberOrder.update();
        if (BigDecimalUtils.greaterThan(currentRemainIntegral, BigDecimal.ZERO) && CollectionUtils.isNotEmpty(memberOrderList)) {
//          List<MemberOrder> memberOrders = nextLink(memberOrderList, topOff);
            MemberOrder nextMemberOrder = memberOrderList.get(0);
            memberOrderList.remove(memberOrder);
            recurrentTask(topOff, nextMemberOrder, currentRemainIntegral, memberOrderList);
        } else {
//          多出来那一部分要暂存起来
            return currentRemainIntegral;
        }
        return BigDecimal.ZERO;
    }

    /**
     * 获得修改比例根据订单id
     * @param auth
     */
    public void getMemberOrder(String auth) {
//      所有积分订单0
        List<Order> orderList = Order.dao.getOrderListByUserIdAndStatus(3, auth);
        Map<String, Order> orderMap = orderList.stream().filter(Order -> Order.getId() != null).collect(
                Collectors.toMap(Order::getId, a -> a, (k1, k2) -> k1));
        List<MemberOrder> memberOrderList = MemberOrder.dao.findByOrderIdByStatus(2);
        List<MemberOrder> currentUserMemberOrderIntegralList = memberOrderList.stream().filter(memberOrder ->
                memberOrder.getOrderId() != null && orderMap.get(memberOrder.getOrderId()) != null).collect(Collectors.toList());

        MemberOrder memberOrder = null;
        Optional<MemberOrder> memberOrderIntegralOptional = currentUserMemberOrderIntegralList.stream().
                filter(memberOrderIntegralOption -> MemberOrderItergralStatusEnum.GET_INTEGRAL.
                        getCode() == memberOrderIntegralOption.getStatus()).findFirst();
//      取出当前要增加的积分订单以及积分封顶倍数
        BigDecimal topOff = getGarde(auth);
        if (memberOrderIntegralOptional.isPresent()) {
            memberOrder = memberOrderIntegralOptional.get();
        } else {
            List<MemberOrder> confirmedmemberOrderList = nextLink(currentUserMemberOrderIntegralList, topOff);
            if (CollectionUtils.isNotEmpty(confirmedmemberOrderList)) {
                memberOrder = confirmedmemberOrderList.get(0);
                memberOrder.setStatus(MemberOrderItergralStatusEnum.GET_INTEGRAL.getCode());
                memberOrder.update();
            }
        }
    }


    /**
     * 每日任务
     */
    public ApiResponse taskEveryDay(String auth, int type) {

        List<MemberIntegralLog> memberIntegralLogList = MemberIntegralLog.dao.findDailyAndIdLog(auth);
        if (memberIntegralLogList.size() >= 1) {
            return new ApiResponse(true, "今天已经做过任务,明天再来吧");
        }

        List<MemberOrder> memberOrderList = MemberOrder.dao.findByOrder(auth);

        List<Order> orderList = Order.dao.findAll();

        List<Order> currentUserOrderList = orderList.stream().filter(order -> order.getUserId() != null && auth.
                equals(order.getUserId()+"")&& new Integer("3").equals(order.getState())).collect(Collectors.toList());
        Map<String, Order> orderMap = currentUserOrderList.stream().filter(Order -> Order.getId() != null).collect(
                Collectors.toMap(Order::getId, a -> a, (k1, k2) -> k1));
        List<MemberOrder> memberOrderListByConfirimRevice = memberOrderList.stream().filter(memberOrder ->
                memberOrder.getStatus() != null  && memberOrder.getStatus().equals( MemberOrderItergralStatusEnum.
                        CONFIRM_THE_RECEIVE .getCode())).collect(Collectors.toList());
        List<MemberOrder> currentUserMemberOrderByConfirimRevice = memberOrderListByConfirimRevice.stream().filter(memberOrder
                -> memberOrder.getOrderId() != null && orderMap.get(memberOrder.getOrderId()) != null).collect(
                Collectors.toList());

        BigDecimal multiRule = this.getGarde(auth);
//      每次签到以及动态都要重新给一次预计可获得积分,剩余积分,更改释放倍数
        for (int i = 0; i < currentUserMemberOrderByConfirimRevice.size(); i++) {
            MemberOrder memberOrder = currentUserMemberOrderByConfirimRevice.get(i);
            BigDecimal deliverMultiple = memberOrder.getDeliverMultiple() == null ? BigDecimal.ZERO : memberOrder.getDeliverMultiple();
            BigDecimal remainIntegral = memberOrder.getRemainIntegral() == null ? BigDecimal.ZERO : memberOrder.getRemainIntegral();
            BigDecimal forcastIntegral = memberOrder.getForecastIntegral() == null ? BigDecimal.ZERO : memberOrder.getForecastIntegral();
            if (BigDecimalUtils.lessThan(deliverMultiple, multiRule) && BigDecimalUtils.equal(remainIntegral, forcastIntegral)) {
                BigDecimal billIntegral = memberOrder.getBillIntegral() == null ? BigDecimal.ZERO : memberOrder.getBillIntegral();
                forcastIntegral = billIntegral.multiply(multiRule);
                BigDecimal currentForcastIntegral = memberOrder.getForecastIntegral() == null ? BigDecimal.ZERO : memberOrder.getForecastIntegral();
                if (BigDecimalUtils.lessThan(currentForcastIntegral, forcastIntegral)) {
                    memberOrder.setDeliverMultiple(multiRule);
                    memberOrder.setRemainIntegral(forcastIntegral);
                    memberOrder.setForecastIntegral(forcastIntegral);
                    memberOrder.setUpdateTime(new Date().getTime());
                    memberOrder.update();
                }
            }
        }


//      从第一单的增值积分里边减掉今天任务得到的积分,获取所有积分订单
        Optional<MemberOrder> memberOrderListByGetIntegral = memberOrderList.stream().filter(memberOrder ->
                memberOrder.getStatus() != null  && memberOrder.getStatus().equals(MemberOrderItergralStatusEnum.
                        GET_INTEGRAL .getCode())&&orderMap.get(memberOrder.getOrderId())!=null).findFirst();
//      选择从那一单开始增加
        BigDecimal remainIntegral = BigDecimal.ZERO;
        MemberOrder memberOrder = null;
        if(memberOrderListByGetIntegral.isPresent()){
            memberOrder = memberOrderListByGetIntegral.get();
            remainIntegral = memberOrder.getRemainIntegral();
        }else{
            if (CollectionUtils.isNotEmpty(currentUserMemberOrderByConfirimRevice)) {
                memberOrder = currentUserMemberOrderByConfirimRevice.get(0);
                memberOrder.setStatus(MemberOrderItergralStatusEnum.GET_INTEGRAL.getCode());
                memberOrder.update();
            }
        }
        BigDecimal currentUserMemberOrderIntegralSum = BigDecimal.ZERO;
        currentUserMemberOrderIntegralSum = currentUserMemberOrderByConfirimRevice.stream().map(MemberOrder::getRemainIntegral).
                reduce(BigDecimal.ZERO, BigDecimalUtilsIfNull::sum);

//      今天做任务获得的积分
        ReverseMultipleRule reverseMultiple = ReverseMultipleRule.dao.getReverse();
        double randomRule = getRandomRule(reverseMultiple).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
        currentUserMemberOrderIntegralSum = currentUserMemberOrderIntegralSum.add(remainIntegral);
        BigDecimal currentGeneratedIntegral = currentUserMemberOrderIntegralSum.multiply(BigDecimal.valueOf(randomRule));
//      本次本单加积分可能加完到下一单(递归)
        BigDecimal topOff = getGarde(auth);
        BigDecimal freezeIntegral = BigDecimal.ZERO;
        if (memberOrder != null) {
            freezeIntegral = recurrentTask(topOff, memberOrder, currentGeneratedIntegral, memberOrderList);
        }else{
            freezeIntegral = currentGeneratedIntegral;
        }

//      这条默认是不需要的
        MemberBillSpeedIntegral memberBillSpeedIntegral = MemberBillSpeedIntegral.dao.getMemberBillSpeedIntegralByUserId(auth);
        if (memberBillSpeedIntegral == null) {
            memberBillSpeedIntegral = new MemberBillSpeedIntegral();
            memberBillSpeedIntegral.setUserIdAndSpeedIntegralAndCoinAndBillCouponAndForecastAndRemainAndReverseAndDailyIncrement(
                    auth, currentGeneratedIntegral, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO
                    , BigDecimal.ZERO);
            memberBillSpeedIntegral.setFreezeIntegral(freezeIntegral);
            memberBillSpeedIntegral.dao.save();
        }
//      总积分(算上今天)
        BigDecimal speedIntegral = memberBillSpeedIntegral.getSpeedIntegral() == null ? BigDecimal.ZERO : memberBillSpeedIntegral.getSpeedIntegral();
        memberBillSpeedIntegral.setSpeedIntegral(speedIntegral.add(currentGeneratedIntegral));

//      今日新增
        Long updateTime = memberBillSpeedIntegral.getUpdateTime();
        int s = 0;
        try {
            s = handleDate(updateTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(s==1){
            BigDecimal dailyIncrement = memberBillSpeedIntegral.getDailyIncrement();
            memberBillSpeedIntegral.setDailyIncrement(dailyIncrement.add(currentGeneratedIntegral));
            log.info("第二次了兄弟");
        }else{
            memberBillSpeedIntegral.setDailyIncrement(currentGeneratedIntegral);
            log.info("第一次兄弟");
        }
//      总共获得的兑货券
        memberBillSpeedIntegral.setAcquireCoupon(memberBillSpeedIntegral.getAcquireCoupon()==null?currentGeneratedIntegral:
                memberBillSpeedIntegral.getAcquireCoupon().add(currentGeneratedIntegral));
//      暂存
        memberBillSpeedIntegral.setFreezeIntegral(memberBillSpeedIntegral.getFreezeIntegral() == null ?
               freezeIntegral: memberBillSpeedIntegral.getFreezeIntegral().add(freezeIntegral));
//      剩余获得积分
        BigDecimal remainSpeedIntegral = memberBillSpeedIntegral.getRemainSpeedIntegral()==null?BigDecimal.ZERO:
                memberBillSpeedIntegral.getRemainSpeedIntegral();
        memberBillSpeedIntegral.setRemainSpeedIntegral(remainSpeedIntegral.subtract(currentGeneratedIntegral));

        memberBillSpeedIntegral.setUpdateTime(new Date().getTime());
        memberBillSpeedIntegral.update();
//      插入日志
        MemberIntegralLog memberIntegralLog = new MemberIntegralLog();
        if (type == 1) {
            memberIntegralLog.setUserIdAndintegralAndIncrementIntegralAndStatusAndCommissionAndReserveAndDesc(
                    auth, 6, memberBillSpeedIntegral.getSpeedIntegral(), currentGeneratedIntegral, true,
                    BigDecimal.ZERO, topOff, "签到获得积分");
            memberIntegralLog.save();
            return new ApiResponse(true, "签到成功");
        }
        if (type == 2) {
            memberIntegralLog.setUserIdAndintegralAndIncrementIntegralAndStatusAndCommissionAndReserveAndDesc(
                    auth, 6, memberBillSpeedIntegral.getSpeedIntegral(), currentGeneratedIntegral, true,
                    BigDecimal.ZERO, topOff, "转发朋友圈获得积分");
            memberIntegralLog.save();
            return new ApiResponse(true, "任务完成");
        }
        return new ApiResponse(true, "任务完成");
    }

    private static int handleDate(long time) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(time);
        Date old = sdf.parse(sdf.format(date));
        Date now = sdf.parse(sdf.format(new Date()));
        long oldTime = old.getTime();
        long nowTime = now.getTime();

        long day = (nowTime - oldTime) / (24 * 60 * 60 * 1000);

        if (day < 1) {  //今天
            SimpleDateFormat format = new SimpleDateFormat("HH:mm");
            return  1 ;
        } else {    //可依次类推
            return 0;
        }
    }

//    public JSONObject getGarde(List<InviteeRelative> inviteeRelativeList, InviteeRelative inviter){
////        List<InviteeRelative> collect = inviteeRelativeList.stream().filter(inviteeRelative1 -> inviteeRelative1.getPrototype() != null &&
////                inviteeRelative1.getPrototype().contains(inviter.getId())).collect(Collectors.toList());
////      找到他的下级
//        List<InviteeRelative> collect = inviteeRelativeList.stream().filter(inviteeRelative1 -> inviteeRelative1.getPrototype()
//                != null &&   inviteeRelative1.getPrototype().contains(inviter.getId())).collect(Collectors.toList());
////      获取到所有会员(粉客,推广者)
//        List<MemberInfo> memberFankeInfoList = MemberInfo.dao.memberFankeInfoList(MemberInfoEnum.SECOND_LEVEL.getCode(),
//                MemberInfoEnum.THIRD_LEVEL.getCode());
//        Map<String, MemberInfo> map = memberFankeInfoList.stream().collect(Collectors.toMap(MemberInfo::getUserId, Function.identity()));
////      是粉客的他的所有下级
//        List<InviteeRelative> fansChildren = collect.stream().filter(inviteeRelative -> inviteeRelative.getUserId() != null && map.containsKey(inviteeRelative.getUserId()))
//                .collect(Collectors.toList());
//        GroupRule groupRule = GroupRule.dao.range(fansChildren.size());
//        List<MemberIntegralLog> dailyAndIdLog = MemberIntegralLog.dao.findYesterDayAndIdLog(inviter.getUserId());
////      取到相对应的积分
//        int groupRuleLevel = 0;
//        if(groupRule!=null&&groupRule.getLevel()!=null){
//            groupRuleLevel = groupRule.getLevel();
//        }
//
////      查找父级级别
//        String inviterId = inviter.getInviterId();
//        if(inviterId==null){
//            return null;
//        }
//        List<InviteeRelative> inviteParentList = inviteeRelativeList.stream().filter(inviteeRelative ->
//                inviteeRelative.getPrototype()!=null&&inviteeRelative.getPrototype().contains(inviterId + "-")).collect(Collectors.toList());
//        int size = inviteParentList.size();
//        GroupRule groupRuleParent = GroupRule.dao.range(size);
//        int groupRuleLevelParent = 0;
//        if(groupRuleParent!=null&&groupRuleParent.getLevel()!=null){
//            groupRuleLevelParent = groupRuleParent.getLevel();
//        }
//
////      级差
//        int differential = groupRuleLevelParent - groupRuleLevel;
//        if(differential<0){
//            differential=0;
//        }
//        int differentialMulti = differential * 10;
//        double percent = ArithUtil.percent(differentialMulti, 100);
//
////      昨天的积分*10
//        double mul = ArithUtil.mul(0.15, percent);
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("id",inviterId);
//        jsonObject.put("integral",mul);
//        return jsonObject;
//    }


    /*------------------------------------------------------------------------------------------------*/

    /**
     * @param acquiredIntegral 已获得的积分
     * @param topOff 兑换券释放倍数的乘积(本次总的)
     * @param memberOrderIntegral   会员订单积分
     * @param memberOrderIntegralListByAuth 订单集合
     * @param currentAwardIntegralCount  这次奖励的积分
     */
//    public ApiResponse exchangeCoin(String id, int type,int bill) {
//        MemberInfo memberInfo = MemberInfo.dao.getMemberFankeInfoByUserId(id);
//        if (null == memberInfo) {
//            Map map = new HashMap();
//            map.put("coin", 0);
//            map.put("billOfShop", 0);
//            if (type == 0) {
//                return new ApiResponse(false, "游客不能可以进行金币兑换功能", map);
//            } else {
//                return new ApiResponse(false, "游客不能可以进行提货券兑换功能", map);
//            }
//        }
////      积分兑换金币比例
//        MemberLevel memberLevel = MemberLevel.dao.getMemberLevel(MemberInfoEnum.THIRD_LEVEL.getCode());
//        if (memberLevel == null || memberLevel.getIntegralExchangeCoinRate() == null ||
//                memberLevel.getIntegralExchangeCoinProportion() == null ||
//                memberLevel.getIntegralExchangeProductProportion() == null) {
//            return new ApiResponse(false, "暂时无法兑换");
//        }
////      所有兑货券
//        int speedIntegral = 0;
//        MemberBillSpeedIntegral memberBillSpeedIntegral = MemberBillSpeedIntegral.dao.getMemberBillSpeedIntegral(id);
//        if (memberBillSpeedIntegral != null) {
////            speedIntegral = memberBillSpeedIntegral.getSpeedIntegral() == null ? 0 : memberBillSpeedIntegral.getSpeedIntegral();
//        }
//        if (speedIntegral < 0) {
//            return new ApiResponse(false, "兑货券太少无法兑换");
//        }
////      准备金
//        int reserves = memberLevel.getReserveProportion() == null ? 0 : memberLevel.getReserveProportion();
//        double reserveProportion = percent(reserves, 100);
//        int reservesBalance = (int) (speedIntegral * reserveProportion);
////      除了准备金剩余的兑货券
//        speedIntegral = speedIntegral - reservesBalance;
////      兑换金币(金币折合成积分有多少个)
//        int integralExchangeCoinProportion = memberLevel.getIntegralExchangeCoinProportion();
//        double integralExchangeCoinPercent = percent(integralExchangeCoinProportion, 100);
//        int convertible = (int) ArithUtil.mul(speedIntegral, integralExchangeCoinPercent);
////      积分转金币汇率
//        int integralExchangeCoinRate = memberLevel.getIntegralExchangeCoinRate();
//        double integralExchangeCoinRatePercent = percent(integralExchangeCoinRate, 100);
//        int coin = (int) (integralExchangeCoinRatePercent * convertible);
////      提货券有多少个
//        int integralExchangeProductProportion = memberLevel.getIntegralExchangeProductProportion()
//                == null ? 0 : memberLevel.getIntegralExchangeProductProportion();
//        double integralExchangeProductPercent = percent(integralExchangeProductProportion, integralExchangeCoinProportion);
//        int billOfShop = (int) (coin * integralExchangeProductPercent);
//        Map map = new HashMap();
////        if (type == 0) {
//        map.put("coin", coin);
//        map.put("billOfShop", billOfShop);
////        }
//        return new ApiResponse(true, "获取成功", map);
//    }
//    public IntegralPool getIntegralPool() {
//        IntegralPool IntegralPool = com.gexin.model.activity.IntegralPool.dao.getIntegralPool();
//        return IntegralPool;
//    }


//    public void getTaskFunction(String id) {
//        inviterService.recurrence(id);
//    }
    /**
     * 积分可以兑换的金币
     *
     * @param
     * @param
     * @return
     */
//    public ApiResponse integralExchangeCoin(String id, int type) {
//        MemberInfo memberInfo = MemberInfo.dao.getMemberFankeInfoByUserId(id);
//        if (null == memberInfo) {
//            Map map = new HashMap();
//            map.put("coin", 0);
//            map.put("billOfShop", 0);
//            if (type == 0) {
//                return new ApiResponse(false, "游客不能可以进行金币兑换功能",map);
//            } else {
//                return new ApiResponse(false, "游客不能可以进行提货券兑换功能", map);
//            }
//        }
////      积分兑换金币比例
//        MemberLevel memberLevel = MemberLevel.dao.getMemberLevel(MemberInfoEnum.THIRD_LEVEL.getCode());
//        if (memberLevel == null || memberLevel.getIntegralExchangeCoinRate() == null ||
//                memberLevel.getIntegralExchangeCoinProportion() == null ||
//                memberLevel.getIntegralExchangeProductProportion() == null) {
//            return new ApiResponse(false, "暂时无法兑换");
//        }
////      所有兑货券
//        int speedIntegral = 0;
//        MemberBillSpeedIntegral memberBillSpeedIntegral = MemberBillSpeedIntegral.dao.getMemberBillSpeedIntegral(id);
//        if (memberBillSpeedIntegral != null) {
////            speedIntegral = memberBillSpeedIntegral.getSpeedIntegral() == null ? 0 : memberBillSpeedIntegral.getSpeedIntegral();
//        }
//        if (speedIntegral < 0) {
//            return new ApiResponse(false, "兑货券太少无法兑换");
//        }
////      准备金
//        int reserves = memberLevel.getReserveProportion() == null ? 0 : memberLevel.getReserveProportion();
//        double reserveProportion = percent(reserves, 100);
//        int reservesBalance = (int) (speedIntegral * reserveProportion);
////      除了准备金剩余的兑货券
//        speedIntegral = speedIntegral - reservesBalance;
////      兑换金币(金币折合成积分有多少个)
//        int integralExchangeCoinProportion = memberLevel.getIntegralExchangeCoinProportion();
//        double integralExchangeCoinPercent = percent(integralExchangeCoinProportion, 100);
//        int convertible = (int) ArithUtil.mul(speedIntegral, integralExchangeCoinPercent);
////      积分转金币汇率
//        int integralExchangeCoinRate = memberLevel.getIntegralExchangeCoinRate();
//        double integralExchangeCoinRatePercent = percent(integralExchangeCoinRate, 100);
//        int coin = (int) (integralExchangeCoinRatePercent * convertible);
////      提货券有多少个
//        int integralExchangeProductProportion = memberLevel.getIntegralExchangeProductProportion()
//                == null ? 0 : memberLevel.getIntegralExchangeProductProportion();
//        double integralExchangeProductPercent = percent(integralExchangeProductProportion, integralExchangeCoinProportion);
//        int billOfShop = (int) (coin * integralExchangeProductPercent);
//        Map map = new HashMap();
////        if (type == 0) {
//            map.put("coin", coin);
//            map.put("billOfShop", billOfShop);
////        }
//        return new ApiResponse(true, "获取成功", map);
//    }


    /**
     * 获取用户信息(积分和金币)
     */
//    public void getMemberInfo(){
//        WeixinUser authUser = getAuthUser();
//        MemberInfo memberInfo = memberActivityService.getMemberInfo(authUser);
//        Map map = memberActivityService.getMemberIntegralAndCoin(memberInfo);
//        map.put("dailyIncrement",memberInfo.getDelaryIncrement()==null?0:memberInfo.getDelaryIncrement());
//        renderJson(map);
//        return;
//    }


    /**
     * 金币兑换成现金
     *
     * @param authUser
     * @return
     */
//    @Before(Tx.class)
//    public ApiResponse coinExchangeMoneyBanck(String authUser, String money) {
//        if(money==null){
//            return new ApiResponse("请输入金额后进行转账");
//        }
//        ApiResponse l = coinExchangeMoneyConvernet(authUser);
//        Map data = (Map) l.getData();
//        BigDecimal moneyBd = new BigDecimal(money);
//        if(moneyBd.compareTo(new BigDecimal("0.5"))<0){
//            return new ApiResponse("最小转出0.5");
//        }
//        String converntmoney =   data.get("balance")+"";
//        BigDecimal convertMoneyBd = new BigDecimal(converntmoney);
//        if (moneyBd.compareTo(convertMoneyBd)==1 ) {
//            return new ApiResponse(false, "提现的金额过大,请重试");
//        }
////      佣金兑换现金比例
//        MemberLevel memberLevel = MemberLevel.dao.getMemberLevel(MemberInfoEnum.THIRD_LEVEL.getCode());
//        double coinExchangeBalancePercent = memberLevel.coinExchangeBalancePercent(memberLevel);
////      手续费
//        BigDecimal subBd = BigDecimal.valueOf(coinExchangeBalancePercent);
//        BigDecimal commission = moneyBd.multiply(subBd);
//        moneyBd = moneyBd.subtract(commission);
//        BigDecimal othermoneyBd = moneyBd.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP);
//        String i = othermoneyBd.toString();
//        MemberCommisionLog memberCommisionLog = new MemberCommisionLog();
//        memberCommisionLog.setMemberCommisionLogByUserId(System.currentTimeMillis() / 1000 + "",moneyBd,
//                1,new Date().getTime(),authUser);
//        WeixinUser user = WeixinUser.dao.findById(authUser);
//        String openid = "";
////        if(user==null){
////            return new ApiResponse(false,"暂时此账户没有与微信绑定关系,无法完成充值");
////        }
////        if(StringUtils.isNotBlank(user.getOpenid())){
////            openid = user.getOpenid();
////        }else if(user.getAppOpenid()==null){
////            openid = user.getAppOpenid();
////        }
////        if(StringUtils.isBlank(openid)){
////            return new ApiResponse(false,"暂时此账户没有与微信绑定关系,无法完成充值");
////
////        }
//
//        MemberCommision memberCommision = MemberCommision.dao;
//        String pathKit = PathKit.getRootClassPath() + "/weixin/cer/zhongke_apiclient_cert.p12";
//        CompanyToPerson companyToPerson = new CompanyToPerson();
//        companyToPerson.transfer("wx001ef33c1c1512d9", "1561327181",
//                pathKit, "osLUVt3PWeur085pobxXULp3zzJs",System.currentTimeMillis() / 1000 + "",
//                i , "金币兑换现金");
//
//        companyToPerson.bankBalance(pathKit);
//        return new ApiResponse(true, "兑换成功");
//    }

//        if (type.equals(ExchangeType.COIN_ENUM.getCode())) {
//            if (coinNum > Integer.parseInt(coin)) {
//                return new ApiResponse(true, "兑换的佣金和兑货券相加大于总积分");
//            }
//          兑换金币数得到的兑货券
//            billOfShopNum = (int) (coinNum / ProductAndCoinPercent);
//        } else if (type.equals(ExchangeType.BILLOFSHOP_ENUM.getCode())) {
//            if (billOfShopNum > Integer.parseInt(billOfShop)) {
//                return new ApiResponse(true, "兑换的佣金和兑货券相加大于总积分");
//            }
//          兑换兑货券获得金币数
//            coinNum = (int) (billOfShopNum * ProductAndCoinPercent);
//        }
//        if (type.equals(ExchangeType.COIN_ENUM.getCode())) {
//            if (coinNum > Integer.parseInt(coin)) {
//                return new ApiResponse(true, "兑换的佣金和兑货券相加大于总积分");
//            }
////          兑换金币数得到的兑货券
//            billOfShopNum = (int) (coinNum / ProductAndCoinPercent);
//        } else if (type.equals(ExchangeType.BILLOFSHOP_ENUM.getCode())) {
//            if (billOfShopNum > Integer.parseInt(billOfShop)) {
//                return new ApiResponse(true, "兑换的佣金和兑货券相加大于总积分");
//            }
////          兑换兑货券获得金币数
//            coinNum = (int) (billOfShopNum * ProductAndCoinPercent);
//        }
    //    BigDecimal billIntegral = new BigDecimal("0");
//    BigDecimal multiReserve = new BigDecimal("0");
//      剩余要减去的积分
//            remainIntegral = memberOrderIntegral.remainIntegral;
//            if(BigDecimalUtils.lessThan(remainIntegral,sumPercentBigDecimal)){
//             }
//            remainIntegral = remainIntegral.subtract(sumPercentBigDecimal);
////          已获得的积分
//            acquiredIntegral = acquiredIntegral.add(sumPercentBigDecimal);
////      今日已获得的积分
//            dailyIncrement = memberOrderIntegral.dailyIncrement;
//            remainIntegral = dailyIncrement.add(sumPercentBigDecimal);
////      倍数的乘积
//            BigDecimal billIntegralAndmultiReserveMultiply = billIntegral.multiply(multiReserve);
////      已经获得的增值积分和总值进行比较，如果小于直接加，如果大于加到第二个里边
//            recurrentTask(acquiredIntegral, billIntegralAndmultiReserveMultiply,
//                    memberOrderIntegral, memberOrderIntegralListByAuth, sumPercent);
////      修改或插入总积分
//        }
//      买金币用的积分
//        int coinNumIntegral = (int) (coinNum * integralExchangeCoinPercent);
//      获得提货券对应的积分数
//        int billOfLadingIntegral = (int) (coinNumIntegral / ProductAndCoinPercent);

//        Integer speedIntegral = memberBillSpeedIntegral.getSpeedIntegral();
//        double percent = MemberLevel.resever(memberLevel);
//        int count = billOfLadingIntegral + coinNumIntegral;
//        int percentReserve = (int) (count * percent);
//        count = count + percentReserve;
//        speedIntegral = speedIntegral - count;
//        if (speedIntegral < 0) {
//            return new ApiResponse(false, "无法兑换,兑换佣金和兑货券总额大于总计分数");
//        }

//        int billOfShopNumMine = memberBillSpeedIntegral.getBillCoupon()==null?0:memberBillSpeedIntegral.getBillCoupon();
//        billOfShopNumMine+=billOfShopNum;
//        BigDecimal coinMine = memberBillSpeedIntegral.getCoin()==null?zero:memberBillSpeedIntegral.getCoin();
//        coinMine+=coinNum;
//         memberBillSpeedIntegral.setSpeedIntegralAndCoinAndBillCouponUpdate(userId, speedIntegral, coinMine, billOfShopNumMine);
//         memberBillSpeedIntegral.update();

//        MemberIntegralLog memberIntegralLog = new MemberIntegralLog();
//        memberIntegralLog.setUserIdAndintegralAndIncrementIntegralAndStatusAndCommissionAndReserveAndDesc(
//                userId + "",4, speedIntegral, count, false, 0, percentReserve,
//                "积分兑换金币以及相应提货券");
//        memberIntegralLog.save();
}
